<template>
  <div id="canvas" style="width:100%;height:280px;"></div>
</template>
<script>
import * as echarts from 'echarts';

export default {
  data() {
    return {
      prices: []
    };
  },
  props: {
    code: String
  },
  watch:{
    code(){
      this.getPrices();
    }
  },
  methods: {
    getPrices() {
      let that = this;

      this.$http.get(`/api/shares/${this.code}/prices`).then(res => {
        let d = res.datas;

        that.echartsOption.series.length = 0;

        that.echartsOption.xAxis.data = d.map(function(m) {
          return `${m.Date}`;
        });

        that.echartsOption.series.push({
          name: '价格',
          type: 'line',
          yAxisIndex: 0,
          data: d.map(function(m) {
            return m.CurrentPrice.toFixed(2);
          }),
          markPoint: {
            data: [
              { type: 'max', name: '最大值' },
              { type: 'min', name: '最小值' }
            ]
          },
          markLine: {
            data: [{ type: 'average', name: '平均值' }]
          }
        });

        that.echartsOption.series.push({
          name: '涨幅',
          type: 'line',
          yAxisIndex: 1,
          data: d.map(function(m) {
            return ((m.CurrentPrice-m.StartPrice)/m.StartPrice * 100).toFixed(2);
          })
        });

        // 使用刚指定的配置项和数据显示图表。
        that.echarts.setOption(that.echartsOption);
      });
    }
  },
  mounted() {
    const $this =this;

    this.$nextTick(() => {
      this.echarts = echarts.init(document.getElementById('canvas'));

      this.echartsOption = {
        grid: {
          left: '10px',
          right: '280px',
          bottom: '0',
          top: '30px',
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            animation: false
          }
        },
        legend: {
          align: 'left',
          data: ['价格', '涨幅']
        },
        xAxis: {
          type: 'category',
          axisLabel: {
            formatter: '{value}'
          },
          axisPointer: {
            show: true,
            label: {
              show: true,
              formatter: '{value}'
            }
          },
          data: []
        },
        yAxis: [
          {
            type: 'value',
            name: '价格(元)',
            min: 0,
            position: 'left',
            axisLabel: {
              formatter: '{value}'
            }
          },
          {
            type: 'value',
            name: '涨幅(%)',
            position: 'right',
            axisLabel: {
              formatter: '{value}'
            }
          }
        ],
        series: []
      };

      // 使用刚指定的配置项和数据显示图表。
      this.echarts.setOption(this.echartsOption);

      this.getPrices();
    });
  },
};
</script>
